#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QTextStream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setCentralWidget(ui->splitter);
    //模型设置
    standardItemModel = new QStandardItemModel(this);
    itemSelectionModel = new QItemSelectionModel(standardItemModel);
    connect(itemSelectionModel, &QItemSelectionModel::currentChanged,
            this, &MainWindow::on_currentIndexChanged);
    //tableView初始化
    ui->tableView->setModel(standardItemModel);
    ui->tableView->setSelectionModel(itemSelectionModel);
    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems);
    //状态栏组件初始化
    lCurFile = new QLabel("文件名", this);
    lCurFile->setMinimumWidth(200);
    lCurCellPos = new QLabel("当前单元格：%d行，%d列", this);
    lCurCellPos->setMinimumWidth(200);
    lCurCellContent = new QLabel("单元格信息", this);
    lCurCellContent->setMinimumWidth(200);
    ui->statusbar->addWidget(lCurFile);
    ui->statusbar->addWidget(lCurCellPos);
    ui->statusbar->addWidget(lCurCellContent);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initModelFromStringList(QStringList &stringList)
{

}

void MainWindow::on_currentIndexChanged(const QModelIndex &current, const QModelIndex &previous)
{
    if (current.isValid()) {
        lCurCellPos->setText(QString::asprintf("当前单元格：%d，%d列", current.row(), current.column()));
        QStandardItem *item = standardItemModel->itemFromIndex(current);
        lCurCellContent->setText("单元格内容：" + item->text());
        QFont font = lCurCellContent->font();
        ui->actFontBold->setChecked(font.bold());
        delete item;
    }
}


void MainWindow::on_actOpen_triggered()
{
    QString curPah = QDir::currentPath() + "/..";
    QString fileName = QFileDialog::getOpenFileName(this, "打开一个文件",
                                                    curPah, "井数据文件(*.txt);;所有文件(*.*");
    QFile file(fileName);
    QStringList stringList;
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream textStream(&file);
//        textStream.setAutoDetectUnicode(true);
        ui->plainTextEdit->clear();
        while (!textStream.atEnd()) {
            QString str = textStream.readLine();
            ui->plainTextEdit->appendPlainText(str);
            stringList.append(str);
        }
        file.close();
        this->lCurFile->setText("当前文件：" + fileName);    //状态栏显示
        initModelFromStringList(stringList);
    }
}
